package com.sunyur.tailor.channel.service.middle.rocketmq;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 *
 * @Author 99288
 * @Description rocketMq 消息发送
**/
@Component
@ConditionalOnProperty(name = "rocketmq.switch", havingValue = "open")
public class RocketProducer {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 同步消费
     */
    public void sync(String msg,String topic) {
        log.info("RocketProducer sync param：{},{}", msg, topic);
        try {
            SendResult sendResult = rocketMQTemplate.syncSend(topic, msg);
            log.info("RocketProducer sync return {}", JSON.toJSONString(sendResult));
        }catch (Exception e){
            log.error("RocketProducer sync exception:{}", e);
        }
    }

    /**
     * 异步消费
     */
    public void aSync(String msg,String topic) {
        log.info("RocketProducer aSync param：{},{}", msg, topic);
        try{
            rocketMQTemplate.asyncSend(topic, msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult){
                    log.info("RocketProducer aSync return {}", JSON.toJSONString(sendResult));
                }
                @Override
                public void onException(Throwable throwable) {
                    log.info("RocketProducer aSync onException:{}", JSON.toJSONString(throwable));
                }
            });
        }catch (Exception e){
            log.error("RocketProducer aSync exception:{}", e);
        }
    }

    /**
     * 转发消费
     */
    public void convertAndSend(String msg,String topic) {
        log.info("RocketProducer convertAndSend param：{},{}", msg, topic);
        try{
            rocketMQTemplate.convertAndSend(topic, msg);
            log.info("RocketProducer aSync return success");
        }catch (Exception e){
            log.error("RocketProducer convertAndSend exception:{}", e);
        }
    }
}